# -*- coding: utf-8 -*-
#实时图像数据的服务器
import threading
import simplejson
__author__ = 'hftec'

from Queue import Queue
import socket
import rtdata_tcp_thread
import multiprocessing
import matplotlib.pyplot as plt
import cv2
resp_cmd = {
    "respCode":200,
    "position":0,
    "img":[]
}

class RtDataTcpServer:
    def __init__(self,img_queue):
        self.img_queue = img_queue
        self.clients= []  #判断是否在客户端连接上
        self.server_run = True
        self.address = ('', 8090)
        self.cmd_queue = Queue()
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # s = socket.socket()
        self.s.bind(self.address)
        self.s.listen(5)
    def start(self):
        # self.is_stop = False
        # threading.Thread(target=self.wait_data).start()
        self.server_thread = threading.Thread(target=self.wait_data).start()#multiprocessing.Process(target=self.wait_data)
        self.wait_thread = threading.Thread(target=self.__wati_cmd).start()
        self.send_process = threading.Thread(target=self.__send_img)
        self.send_process.start()
        self.__send_img()
    def wait_data(self):
        print "tcp server start\r\n"
        try:
            while(self.server_run):
                client, addr = self.s.accept()
                print 'got connected from',addr


                #ss.send('byebye')
                thread =  rtdata_tcp_thread.TcpThread(client,self.cmd_queue)
        except KeyboardInterrupt:
            self.close()
    # def stop_tcp_server(self):
    #     # self.is_stop = True
    #     self.close()
    def __wati_cmd(self):
        while(self.server_run):
            que = self.cmd_queue.get()
            cmd = que["cmd"]
            client = que["client"]
            print("cmd",cmd)
            if(cmd["opType"] == 5):
                self.clients.append(client)
            elif(cmd["opType"] == 6):
                self.clients.remove(client)
            # client.send(simplejson.dumps(resp_cmd))

    def __send_img(self):
        while(self.server_run):
            img = self.img_queue.get()
            # resp_cmd["img"] = img.dumps()
            cv2.imshow("server", img)

            if cv2.waitKey(1) & 0xFF == ord('q'):
                # fobj.flush()
                # fobj.close()
                cv2.destroyAllWindows()
                break
            for c in (self.clients):
                try:
                    c.send(img.dumps())
                except socket.error as msg:
                    print(msg)
                    self.clients.remove(c)
    def close(self):
        self.server_run = False
        # self.send_process.terminate()
        self.s.close()